const express = require('express')
const path = require('path')
const dbhelper = require('./my_modules/DBHelper')

const app = express();
app.use(express.urlencoded({
    extended: false
}));
app.use(express.json());

app.use(express.static("./public"));

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.get('/', (req, res) => {
    // res.sendFile(`${__dirname}/views/index.html`)
    res.render('index')
})
app.get('/index', (req, res) => {
    // res.sendFile(`${__dirname}/views/index.html`)
    res.redirect('/')
})
app.get('/detail', (req, res) => {
    res.render('detail')
})
app.get('/detail/:model', async (req, res) => {
    console.log(req.params);
    //1.准备sql语句的参数
    let params = [
        req.params.model
    ]
    //2.准备sql语句
    let sql = "SELECT `id`,`name`,`cover`,`title`,`describe`,`price` FROM `goods` WHERE `model` = ?";
    //3.执行sql语句
    try {
        let result = await dbhelper.exec(sql, params);
        console.log(result);
        res.render('detail', result[0])
    } catch (error) {
        console.log(error);
    }
})

app.get('/chart', (req, res) => {
    res.render('chart')
})

app.get('/login', (req, res) => {
    console.log(req.query);
    let user = req.query;
    dbhelper.exec(
        "SELECT `pwd`,`id` FROM `user` WHERE `name`=?",
        [user.name]
    ).then((message) => {
        if (user.pwd == message[0].pwd) {
            console.log('登录成功');
            res.json({
                code: 200,
                msg: '登录成功',
                data: {uid:message[0].id},
            })
        } else {
            console.log('登录失败');
            res.json({
                code: 401,
                msg: '登录失败',
                data: null,
            })
        }
    })
})
app.post('/register', (req, res) => {
    console.log(req.body);
    let user = req.body;
    dbhelper.exec(
        "INSERT INTO `user` (`name`,`pwd`,`mobile`,`email`) VALUES (?,?,?,?)",
        [user.name, user.pwd, user.mobile, user.email]
    ).then(() => {
        console.log('注册成功');
        res.json({
            msg: "注册成功",
            code: 200,
        })
    }).catch(() => {
        console.log('注册失败');
        res.json({
            msg: "注册失败",
            code: -200,
        })
    })
})

// 查找
app.post("/regphone", async (req, res) => {
    //1.准备sql语句的参数
    let params = [
        req.body.mobile
    ]
    console.log(req.body);
    console.log(params);
    //2.准备sql语句
    let sql = "SELECT * FROM `user` WHERE `mobile`= ? ";
    //3.执行sql语句
    try {
        let result = await dbhelper.exec(sql, params);
        console.log(result);
        let isSearch = result.length >= 1 ? false : true;
        res.json({
            msg: isSearch ? "手机号可注册" : "手机号已被注册",
            code: isSearch ? 200 : -200,
        })
    } catch (error) {
        console.log(error);
        res.json({
            msg: "查找失败",
            error
        })
    }
})

app.post("/searchCart", async (req, res) => {
    //1.准备sql语句的参数
    let params = [
        req.body.uid
    ]
    //2.准备sql语句
    let sql = "SELECT a.id,gid,name,num,title,cover,price FROM `cart` a JOIN `goods` b ON a.gid = b.id WHERE a.uid = ? AND a.`status` = 1";
    //3.执行sql语句
    try {
        let result = await dbhelper.exec(sql, params);
        res.json({
            msg: "查询成功",
            code: 200,
            data: result
        })
    } catch (error) {
        res.json({
            msg: "查询失败",
            code: -200,
            error
        })
    }
})
app.post("/delCart", async (req, res) => {
    //1.准备sql语句的参数
    let params = [
        req.body.id
    ]
    //2.准备sql语句
    let sql = "UPDATE `cart` SET `status` = 0 WHERE id = ?";
    //3.执行sql语句
    try {
        let result = await dbhelper.exec(sql, params);
        console.log(result);
        res.json({
            msg: "删除成功",
            code: 200,
            data: result
        })
    } catch (error) {
        res.json({
            msg: "删除失败",
            code: -200,
            error
        })
    }
})
app.post("/updateCart", async (req, res) => {
    //1.准备sql语句的参数
    let params = [
        req.body.num,
        req.body.id
    ]
    //2.准备sql语句
    let sql = "UPDATE `cart` SET `num` = ? WHERE id = ?";
    //3.执行sql语句
    try {
        let result = await dbhelper.exec(sql, params);
        console.log(result);
        res.json({
            msg: "修改成功",
            code: 200,
            data: result
        })
    } catch (error) {
        res.json({
            msg: "修改失败",
            code: -200,
            error
        })
    }
})
app.post("/insertCart", async (req, res) => {
    //1.准备sql语句的参数
    let params = [
        req.body.uid,
        req.body.gid,
        req.body.num,
    ]
    //2.准备sql语句
    let sql = "INSERT INTO `cart` (`uid`,`gid`,`num`) VALUES (?, ?,?)";
    //3.执行sql语句
    try {
        let result = await dbhelper.exec(sql, params);
        console.log(result);
        res.json({
            msg: "插入成功",
            code: 200,
            data: result
        })
    } catch (error) {
        res.json({
            msg: "插入失败",
            code: -200,
            error
        })
    }
})

app.listen(8080)